Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Input
Imports Biller.core

Namespace control
	Public Class AutoCompleteComboBox
		Inherits ComboBox
		Private _acm As AutoCompleteManager
		Private _textBox As TextBox
		Private _oldSelStart As Integer
		Private _oldSelLength As Integer
		Private _oldText As String

		Public ReadOnly Property AutoCompleteManager() As AutoCompleteManager
			Get
				Return _acm
			End Get
		End Property

		Public Sub New()
			Me.IsEditable = True
			Me.IsTextSearchEnabled = False
			AddHandler Me.GotMouseCapture, AddressOf AutoCompleteComboBox_GotMouseCapture

			_acm = New AutoCompleteManager()
		End Sub

		Private Sub AutoCompleteComboBox_GotMouseCapture(sender As Object, e As MouseEventArgs)
			_oldSelStart = _textBox.SelectionStart
			_oldSelLength = _textBox.SelectionLength
			_oldText = _textBox.Text
		End Sub

		Protected Overrides Sub OnPreviewKeyDown(e As KeyEventArgs)
			If _acm.AutoCompleting Then
				Return
			End If
			If e.Key = Key.Up OrElse e.Key = Key.Down Then
				Me.SelectedValue = Me.Text
			End If
			MyBase.OnPreviewKeyDown(e)
		End Sub

		Protected Overrides Sub OnDropDownOpened(e As EventArgs)
			_acm.Disabled = True
			Me.IsTextSearchEnabled = True
			Me.SelectedValue = Text

			MyBase.OnDropDownOpened(e)

			If Me.SelectedValue Is Nothing Then
				Me.Text = _oldText
				_textBox.SelectionStart = _oldSelStart
				_textBox.SelectionLength = _oldSelLength
			End If
		End Sub

		Protected Overrides Sub OnDropDownClosed(e As EventArgs)
			MyBase.OnDropDownClosed(e)
			_acm.Disabled = False
			Me.IsTextSearchEnabled = False
		End Sub

		Public Overrides Sub OnApplyTemplate()
			MyBase.OnApplyTemplate()
			_textBox = TryCast(GetTemplateChild("PART_EditableTextBox"), TextBox)
			_acm.AttachTextBox(_textBox)
		End Sub
	End Class
End Namespace
